import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    // 用户信息
    token: localStorage.getItem("token") || null,
    userId: Number(localStorage.getItem("userId"))  || 0,
    name: localStorage.getItem("name") || "",
    avatar: localStorage.getItem("avatar") || "",
    gender: localStorage.getItem("gender") || "",
    isVip: localStorage.getItem("isVip") || false
  },
  mutations: {
    // 设置 Token
    setToken(state, token) {
      state.token = token;
      localStorage.setItem("token", token);
    },
    // 设置用户信息
    setUserInfo(state, { userId, name, avatar, gender, isVip }) {
      if (userId) {
        state.userId = userId;
        localStorage.setItem("userId", userId);
      }
      if (name) {
        state.name = name;
        localStorage.setItem("name", name);
      }
      if (avatar) {
        state.avatar = avatar;
        localStorage.setItem("avatar", avatar);
      }
      if (gender) {
        state.gender = gender;
        localStorage.setItem("gender", gender);
      }
      if (isVip) {
        state.isVip = isVip;
        localStorage.setItem("isVip", isVip);
      }
    },
    // 登出，清空用户信息
    logout(state) {
      state.token = null;
      state.userId = null;
      state.name = "";
      state.avatar = "";
      state.gender = "";
      state.isVip = false;

      localStorage.removeItem("token");
      localStorage.removeItem("userId");
      localStorage.removeItem("name");
      localStorage.removeItem("avatar");
      localStorage.removeItem("gender");
      localStorage.removeItem("isVip");
    }
  },
  actions: {
    // 登录操作
    login({ commit }, { token, userInfo }) {
      commit("setToken", token);
      commit("setUserInfo", userInfo);
    },
    // 退出登录操作
    async logout({ commit }) {
      try {
        // 调用退出登录 API
        const { logout } = await import('@/api/user/index');
        await logout();
      } catch (error) {
        console.error('退出登录失败:', error);
      } finally {
        // 无论 API 调用成功与否，都清除本地用户信息
        commit("logout");
      }
    }
  },
  getters: {
    // 是否已登录
    isAuthenticated: (state) => !!state.token,
    // 用户信息
    userInfo: (state) => ({
      userId: state.userId,
      name: state.name,
      avatar: state.avatar,
      gender: state.gender,
      isVip: state.isVip
    })
  }
});